package everydaydo;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import javazoom.jl.decoder.JavaLayerException;
import javazoom.jl.player.Player;
import util.DateUtil;

/**
 * 判断魔兽世界服务器状态，当服务器状态可用时播放指定的音乐,默认每隔30秒刷新一次结果
 * 
 * @author Administrator
 * 
 */
public class WoWStatus {

	private final static String wowurl = "http://www.battlenet.com.cn/wow/zh/status";
	private final static String musicsrc = "D:/音乐/激情音乐/亡灵序曲.mp3";
	private final static int frequency = 30;

	/*
	 * 
	 */
	public static void main(String[] args) {
		String serveName = "艾萨拉";
		boolean goon = true;
		while (goon) {
			boolean statue = checkStatue(serveName);
			if (statue) {
				goon = false;
				serverIsOnline();
			}
			String info = (DateUtil.getStringFromNowDate() + "  " + serveName + "   ")
					+ (statue ? "可用" : "不可用");
			System.out.println(info);
			try {
				Thread.sleep(1000 * frequency);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * 
	 * @param serverName
	 * @return
	 */
	public static boolean checkStatue(String serverName) {
		BufferedReader in = null;
		try {
			URL url = new URL(wowurl);
			HttpURLConnection connection = (HttpURLConnection) url
					.openConnection();
			connection.setConnectTimeout(5000);
			connection.setRequestMethod("GET");
			if (connection.getResponseCode() != 200) {
				System.out.println("faile: " + connection.getResponseCode());
				return false;
			}
			in = new BufferedReader(new InputStreamReader(url.openStream(),
					"utf-8"));
			String nextLine;
			StringBuilder sb = new StringBuilder();
			while ((nextLine = in.readLine()) != null) {
				sb.append(nextLine);
			}
			if (!"".equals(sb)) {
				int index1 = sb.indexOf(serverName);
				int index2 = sb.indexOf("<td class=\"population\"", index1);
				int index3 = sb.indexOf("</span>", index2);
				String statue = sb.substring(index3 - 15, index3 - 1).trim();
				if ("不可用".equals(statue)) {
					return false;
				} else {
					return true;
				}

			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	public static void serverIsOnline() {
		Player play;
		try {
			BufferedInputStream inputStream = new BufferedInputStream(
					new FileInputStream(musicsrc));
			play = new Player(inputStream);
			play.play();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (JavaLayerException e) {
			e.printStackTrace();
		}
	}
}
